package com.hue.springbootvalidation.exception;

import com.hue.springbootvalidation.utils.Error;
import com.hue.springbootvalidation.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一异常处理
 * @author yfq
 */
@ControllerAdvice(basePackages = "com.hue.springbootvalidation.controller")
@ResponseBody
public class ExcHandler {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validationHandler(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();
        Map<String, String> data = new HashMap<>();
        for (FieldError error : errors) {
            String field = error.getField();
            String message = error.getDefaultMessage();
            data.put(field, message);
        }
        return R.error(Error.VALIDATION_ERROR.getCode(), Error.VALIDATION_ERROR.getMsg()).put("data", data);
    }

    @ExceptionHandler(value = Exception.class)
    public R globalHandler(Exception e) {
        return R.error(Error.UNKNOWN_ERROR.getCode(), Error.UNKNOWN_ERROR.getMsg()).put("data", e.getMessage());
    }
}
